class Route < ActiveRecord::Base
  has_and_belongs_to_many :workers
  has_and_belongs_to_many :comments
  has_and_belongs_to_many :events
  belongs_to  :chain
  belongs_to  :grade
  belongs_to  :color

  validates_presence_of :name, :color_id, :grade_id, :chain, :build
  validates_format_of :name, :with => /[\w\d\.\:\-\_\s]+/

  attr_accessor :workers_list
    after_save :update_workers

  def route_workers_to_link
    self.workers.collect{|x| 
      x.to_link}.join(", ").html_safe
  end
  
  def to_link
    "<a href=\"/routes/#{self.id}\" >#{self.name}</a>".html_safe
  end

  private 

  def <=>(x)
    x.created_at <=> self.created_at
  end

  def update_workers
    self.workers.delete_all
    selected_workers = workers_list.nil? ? [] : workers_list.keys.collect{|id| Worker.find_by_id(id)}
    selected_workers.each {|worker| self.workers << worker}
  end

  def self.all_by_grades
    self.all.sort{|x, y|
      y.grade <=> x.grade
    }
  end

  def self.all_by_bauarbeiter
    self.all.sort{|x, y|
      x.workers.join <=> y.workers.join
    }
  end
  
end
